package com.hnblc.blcwms.rest.config;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

/**
 * @Description <br>
 * @ClassName LocalDateTimeSerializerConfig <br>
 * @Author linsong <br>
 * @date 2019.12.17 15:10 <br>
 */
@Configuration
public class LocalDateTimeSerializerConfig {


    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    // 兼容Date和LocalDateTime
    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern));
    }


    public LocalDateTimeSerializer localDateTimeSerializer(){
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            builder.deserializersByType(

                        new HashMap<Class<?>, JsonDeserializer<?>>() {
                            private static final long serialVersionUID = 4537615678578559810L;

                            {
                                put(LocalDateTime.class, localDateTimeDeserializer());
                            }
                        }
                );
            builder.serializerByType(LocalDateTime.class, localDateTimeSerializer());
            };

    }
}
